<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher
			v-if="searchBar"
			v-model="searchData"
			@search="getTableData"
			@reset="onSearchReset"
			:showToggleAdvanced="true"
			:defaultExpandAdvanced="false"
		>
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<!-- ===== 核心搜索条件（常用） ===== -->
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="Name_FormItem" prop="Name">
							<template #label>
								<WtmLabelTooltip label="SKU名称" tooltip="SKU的完整名称，如：红色连衣裙-L码" />
							</template>
							<el-input v-model="searchData.Name" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="Code_FormItem" prop="Code">
							<template #label>
								<WtmLabelTooltip label="SKU编码" tooltip="SKU唯一编码，用于系统内标识SKU" />
							</template>
							<el-input v-model="searchData.Code" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="MaterialName_FormItem" prop="MaterialName">
							<template #label>
								<WtmLabelTooltip label="物料名称" tooltip="物料名称" />
							</template>
							<el-input v-model="searchData.MaterialName" clearable placeholder="请输入物料名称"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="MaterialCode_FormItem" prop="MaterialCode">
							<template #label>
								<WtmLabelTooltip label="物料编码" tooltip="物料编码" />
							</template>
							<el-input v-model="searchData.MaterialCode" clearable placeholder="请输入物料编码"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="State_FormItem" prop="State">
							<template #label>
								<WtmLabelTooltip label="状态" tooltip="SKU当前状态" />
							</template>
							<el-select v-model="searchData.State" clearable>
								<el-option key="启用" value="启用" label="启用"></el-option>
								<el-option key="禁用" value="禁用" label="禁用"></el-option>
								<el-option key="废弃" value="废弃" label="废弃"></el-option>
							</el-select>
						</el-form-item>
					</el-col>

					<!-- ===== 高级搜索条件（可展开） ===== -->
					<template v-if="showAdvanced">
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="ErpId_FormItem" prop="ErpId">
								<template #label>
									<WtmLabelTooltip label="金蝶ERP编号" tooltip="与外部ERP系统同步时使用的标识符" />
								</template>
								<el-input v-model="searchData.ErpId" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="LastInStockTime_FormItem" prop="LastInStockTime">
								<template #label>
									<WtmLabelTooltip label="最近入库时间" tooltip="SKU最近一次入库的时间" />
								</template>
								<el-date-picker v-model="searchData.LastInStockTime" clearable></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="SelectedAttributesIds_FormItem" prop="SelectedAttributesIds">
								<template #label>
									<WtmLabelTooltip label="SKU属性" tooltip="SKU的具体属性组合，如：红色+L码" />
								</template>
								<el-input v-model="searchData.SelectedAttributesIds" multiple :data="stateData.AllSysMaterialAttributeValues" clearable></el-input>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="compactSearchBar" class="compact-search-bar">
			<el-form :model="searchData" class="search-form">
				<!-- 第一行：物料信息 -->
				<div class="search-row">
					<div class="row-label">SKU信息</div>
					<div class="row-fields">
						<el-form-item prop="MaterialName">
							<el-input v-model="searchData.Name" clearable placeholder="SKU名称" />
						</el-form-item>
						<el-form-item prop="MaterialCode">
							<el-input v-model="searchData.Code" clearable placeholder="SKU编码" />
						</el-form-item>
					</div>
				</div>

				<!-- 第二行：ERP信息 -->
				<div class="search-row">
					<div class="row-label">ERP信息</div>
					<div class="row-fields">
						<el-form-item prop="ErpName">
							<el-input v-model="searchData.ErpName" clearable placeholder="ERP名称" />
						</el-form-item>
						<el-form-item prop="ErpId">
							<el-input v-model="searchData.ErpId" clearable placeholder="ERP编号" />
						</el-form-item>
						<el-form-item prop="ErpModel">
							<el-input v-model="searchData.ErpModel" clearable placeholder="ERP型号" />
						</el-form-item>
						<div class="search-buttons">
							<el-button type="primary" :icon="Search" @click="getTableData">查询</el-button>
							<el-button :icon="Refresh" @click="onSearchReset">重置</el-button>
						</div>
					</div>
				</div>
			</el-form>
		</div>

		<div v-if="toolbar">
			<WtmButton
				v-if="entityId"
				v-auth="'/api/SysMaterialSku/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysMaterialSku/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysMaterialSku/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysMaterialSku/SysMaterialSkuExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>

		<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container">
							<template v-if="props.selectable">
								<WtmButton icon="fa fa-check" type="primary" :is-text="true" button-text="选取" @click="emit('select', scope.row)" />
							</template>
							<template v-else>
								<WtmButton
									v-auth="'/api/SysMaterialSku/Edit'"
									:is-text="true"
									icon="fa fa-pencil-square"
									type="warning"
									:button-text="$t('message._system.common.vm.edit')"
									@click="OnEditRowClick(scope.row)"
								/>
								<WtmButton
									v-auth="'/api/SysMaterialSku/{id}'"
									:is-text="true"
									icon="fa fa-info-circle"
									type="info"
									:button-text="$t('message._system.common.vm.detail')"
									@click="OnDetailsRowClick(scope.row)"
								/>
								<WtmButton
									v-auth="'/api/SysMaterialSku/BatchDelete'"
									icon="fa fa-trash"
									type="danger"
									:button-text="$t('message._system.common.vm.delete')"
									:confirm="$t('message._system.common.vm.deletetip')"
									:is-text="true"
									@click="onDelete(scope.row)"
								/>
							</template>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>
	</div>
</template>

<script setup lang="ts" name="物料SKU;true;HengTong.Areas.SupplyChain.Controllers;SysMaterialSku">
import ElMessage from 'element-plus/es/components/message/index';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed, watch } from 'vue';
import { Search, Refresh } from '@element-plus/icons-vue';
import { SysMaterialSkuApi as api } from '/@/views/supplychain/sysmaterialsku/api';
import { ISysMaterialSkuView, ISysMaterialSkuQuery } from '/@/views/supplychain/sysmaterialsku/api/interface';
import other from '/@/utils/other';
import { IViewModel, ISysSelectType } from '/@/types/common';

const ci = getCurrentInstance() as any;
const loading = ref(false);
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 是否作为选择器使用，展示“选取”操作 */
		selectable?: boolean;
		/** 是否显示紧凑搜索栏 */
		compactSearchBar?: boolean;
		/** 默认筛选 */
		filters?: ISysMaterialSkuQuery;
		/** 主表ID */
		entityId?: string | null;
		/** 物料SKUID */
		materialSkuName?: string | null;
		/** 物料ID */
		materialId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		selectable: false,
		compactSearchBar: false,
		filters: () => ({}),
		entityId: null,
		materialSkuName: null,
		materialId: null,
	}
);

const emit = defineEmits<{
	(e: 'select', row: ISysMaterialSkuView): void;
}>();

const stateData = reactive({
	AllSysMaterials: [] as ISysSelectType[],
	AllSysMaterialAttributeValues: [] as ISysSelectType[],
});

const searchData = ref<ISysMaterialSkuQuery>({
	Name: props.materialSkuName || null,
	Code: null,
	ErpId: null,
	State: null,
	LastInStockTime: null,
	MaterialId: props.materialId || null,
	MaterialName: null,
	MaterialCode: null,
	SelectedAttributesIds: null,
});

// 定义变量内容
const tableRef = ref();
const tableData = ref({
	// 列表数据（必传）s
	data: [],
	// 表头内容（必传，注意格式）按优先级排序
	header: [
		{ title: 'SKU名称', key: 'Name', type: 'text', isCheck: true },
		{ title: 'SKU编码', key: 'Code', type: 'text', isCheck: true },
		{ title: '所属物料', key: 'MaterialName', type: 'text', isCheck: true },
		{ title: 'SKU属性', key: 'AttributesName', type: 'text', isCheck: true },
		{ title: '状态', key: 'State', type: 'text', isCheck: true },
		{ title: '条形码', key: 'BarCode', type: 'text', isCheck: true },
		{ title: '含税单价', key: 'TaxPrice', type: 'text', isCheck: true },
		{ title: '单价', key: 'Price', type: 'text', isCheck: true },
		{ title: '计量单位', key: 'UnitName', type: 'text', isCheck: true },
		{ title: '详情', key: 'Description', type: 'text', isCheck: true },
		{ title: '最近入库时间', key: 'LastInStockTime', type: 'text', isCheck: true, sortable: true },
		{ title: '金蝶ERP编号', key: 'ErpId', type: 'text', isCheck: true },
		{ title: '金蝶ERP名称', key: 'ErpName', type: 'text', isCheck: true },
		{ title: '金蝶ERP型号', key: 'ErpModel', type: 'text', isCheck: true },
		{ title: '备注', key: 'Remark', type: 'text', isCheck: true },
	],
	// 配置项（必传）
	config: {
		total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		// 仅在选择器模式下显示操作列（用于“选取”按钮）
		isOperate: props.selectable,
	},
});
// 初始化表格数据
const getTableData = async () => {
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		other.setFormError(ci, error);
	}
};
const OnCreateClick = () => {
	// 如果有 entityId，传递给新增页面
	const data = props.entityId ? { MaterialId: props.entityId } : null;
	other.openDialog(ci.proxy.$t('message._system.common.vm.add'), CreateDialog, data, getTableData);
};

const OnEditRowClick = (row: ISysMaterialSkuView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.edit'), EditDialog, row, getTableData);
};

const OnDetailsRowClick = (row: ISysMaterialSkuView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.detail'), DetailsDialog, row, getTableData);
};

// 删除
const onDelete = (row: ISysMaterialSkuView) => {
	const ids = [row.ID] as (string | number)[];
	api()
		.delete(ids)
		.then(() => {
			getTableData();
		});
};

//批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysMaterialSkuView) => x.ID) as (string | number)[];
	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			// 先清除选择状态
			tableRef.value?.clearSelection();
			// 再重新获取数据
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy.$t('message._system.common.vm.error'));
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};
// 添加计算属性判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

const OnImportClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.import'), ImportDialog, null, getTableData);
};

const onExport = () => {
	const selected = tableRef.value.getSelectedRows();
	if (selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 搜索重置事件 - 保护从父组件传入的参数不被清空
const onSearchReset = () => {
	// 重置所有搜索字段
	searchData.value.ErpId = '';
	searchData.value.MaterialName = '';
	searchData.value.Name = '';
	searchData.value.Code = '';

	// 如果有物料ID，需要恢复它
	if (props.materialId || props.entityId) {
		searchData.value.MaterialId = props.materialId || props.entityId;
	} else if (props.materialSkuName) {
		searchData.value.Name = props.materialSkuName;
	}

	// 重新加载数据
	getTableData();
};

// 监听 entityId 变化，设置搜索条件
watch(
	() => props.entityId,
	(newEntityId) => {
		if (newEntityId) {
			searchData.value.MaterialId = newEntityId;
			getTableData();
		}
	},
	{ immediate: true }
);

// 页面加载时
onMounted(() => {
	loading.value = true;
	const promises: Promise<any>[] = [];

	// 只有在显示搜索条件时才加载下拉列表数据
	if (props.searchBar) {
		promises
			.push
			// other.getSelectList('/api/SysMaterialSku/GetSysMaterials', [], false).then((x) => (stateData.AllSysMaterials = x)),
			// other.getSelectList('/api/SysMaterialSku/GetSysMaterialAttributeValues', [], false).then((x) => (stateData.AllSysMaterialAttributeValues = x))
			();
	}

	// 如果有 entityId，设置到搜索条件中
	if (props.entityId) {
		searchData.value.MaterialId = props.entityId;
	}

	// 总是需要加载表格数据
	promises.push(getTableData());

	Promise.allSettled(promises).finally(() => {
		loading.value = false;
	});
});
</script>

<style scoped lang="scss">
.compact-search-bar {
	background: #fff;
	padding: 8px 12px;
	margin-bottom: 8px;

	.search-form {
		.search-row {
			display: flex;
			align-items: center;
			padding: 4px 0;

			.row-label {
				min-width: 70px;
				font-size: 13px;
				color: #606266;
				padding-right: 12px;
			}

			.row-fields {
				flex: 1;
				display: flex;
				flex-wrap: wrap;
				gap: 8px;

				:deep(.el-form-item) {
					margin: 0;
					flex: 1;
					min-width: 180px;

					.el-input {
						width: 100%;
					}

					.el-input__wrapper {
						background-color: #f5f7fa;
						box-shadow: none;
						padding: 0 8px;

						&:hover {
							background-color: #fff;
						}

						&.is-focus {
							background-color: #fff;
						}
					}

					.el-input__inner {
						height: 28px;
						line-height: 28px;

						&::placeholder {
							color: #a8abb2;
							font-size: 12px;
						}
					}
				}

				.search-buttons {
					display: flex;
					gap: 8px;
					margin-left: 8px;

					.el-button {
						height: 28px;
						padding: 0 12px;
						font-size: 12px;
					}
				}
			}
		}
	}
}

// 响应式设计
@media screen and (max-width: 768px) {
	.compact-search-bar {
		.search-form {
			.search-row {
				flex-direction: column;
				align-items: flex-start;

				.row-label {
					margin-bottom: 4px;
				}

				.row-fields {
					width: 100%;

					:deep(.el-form-item) {
						width: 100%;
						min-width: auto;
					}

					.search-buttons {
						width: 100%;
						margin-left: 0;
						margin-top: 4px;
					}
				}
			}
		}
	}
}
</style>
